/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int result = 0;

    int dfs(TreeNode* root)
    {
        if(!root)
            return 0;

        int left = max(dfs(root->left), 0);
        int right = max(dfs(root->right), 0);
        result = max(root->val + left + right, result);
        return max(0, max(left, right))+root->val;
    }

    int maxPathSum(TreeNode* root) {
        if(!root)
            return 0;
        result = root->val;
        dfs(root);
        return result;
    }
};